<?
		define('DORB',true);
		require('dorb_init.php');

		/*
					'vrachten_klant' 			=> 'Ordertabel gejoint met klant en met accountmanager',
					'klachten' 					=> 'Klachtentabel gejoint met klant en met accountmanager',
					'resources' 				=> 'Ingezet aantal kilometers per resource'
		*/
		
		if (empty($_POST['Rapportage_type']))
		{
			setLastFormResult(0,'Gelieve een rapportage te kiezen.');
			redirect('genereer-excel');
		}
		
		$bestaand = array('vrachten_klant','klachten','resources');
		if (in_array($_POST['Rapportage_type'],$bestaand))
		{
			header("Content-type: text/csv");
			header("Content-Disposition: attachment; filename=" . $_POST['Rapportage_type'] . ".csv");
			header("Pragma: no-cache");
			header("Expires: 0");
		}
			
		$first=true;	
			
		switch ($_POST['Rapportage_type']) 
		{
			case 'vrachten_klant':
				$r=$mysqli->query('SELECT * FROM vrachten v LEFT JOIN gebruiker g ON v.aanmaker=g.email LEFT JOIN bedrijf b ON g.bedrijf=b.ID');
				break;
				
			case 'klachten':
				$r=$mysqli->query('SELECT * FROM feedback');
				break;
				
			case 'resources':
				$r=$mysqli->query('SELECT * FROM oplegger o LEFT JOIN ritten r ON o.kenteken=r.oplegger LEFT JOIN ritten_vrachten rv ON r.ID=rv.rit LEFT JOIN vrachten v ON rv.vracht=v.ID');
				break;
			
			default:
				setLastFormResult(0,'Gelieve een rapportage te kiezen.');
				redirect('genereer-excel');
		}
		
		$cells = '';
		
		while ($row=$r->fetch_assoc())
		{
			if ($first)
			{
				foreach ($row as $header => $cell)
				{
					echo $header . "\t";
					$cells .= $cell . "\t";
				}
				echo "\n";
				echo $cells . "\n";
				
				unset($cells);
				$first=false;
			}
			else
			{
				foreach ($row as $header => $cell)
				{
					echo $cell . "\t";
				}
				echo "\n";
			}
		}
?>